package com.js.auth.server.module.client.service.impl;

import com.js.auth.server.module.client.entity.AuthClient;
import com.js.auth.server.module.client.entity.AuthClientSer;
import com.js.auth.server.module.client.mapper.AuthClientMapper;
import com.js.auth.server.module.client.mapper.AuthClientSerMapper;
import com.js.auth.server.module.client.service.AuthClientService;
import com.js.common.exception.auth.ClientInvalidException;
import com.js.common.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author ygl
 * @create 2018-10-31
 * @DESCRIPTION
 **/
@Service
public class AuthClientServiceImpl extends BaseServiceImpl<AuthClient> implements AuthClientService {

    @Autowired
    private AuthClientMapper authClientMapper;

    @Autowired
    private AuthClientSerMapper authClientSerMapper;

    @Override
    public void validate(String clientId, String secret) throws Exception {
        AuthClient client = new AuthClient();
        client.setCode(clientId);
        client = authClientMapper.selectOne(client);
        if(client==null||!client.getSecret().equals(secret)){
            throw new ClientInvalidException("Client not found or Client secret is error!");
        }
    }

    @Override
    public void modifyClientServices(String id, String clients) {
        authClientSerMapper.deleteByServiceId(id);
        if (!StringUtils.isEmpty(clients)) {
            String[] mem = clients.split(",");
            for (String m : mem) {
                AuthClientSer clientService = new AuthClientSer();
                clientService.setServiceId(m);
                clientService.setClientId(id+"");
                authClientSerMapper.insertSelective(clientService);
            }
        }
    }

    @Override
    public List<AuthClient> getClientServices(String id) {
        return authClientMapper.selectAuthorityServiceInfo(id);
    }
}
